package ctn.dao.hibernate.impl;

import java.sql.SQLException;

import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.stereotype.Component;

import ctn.dao.inteface.CTNCPALogDao;
import ctn.hibernate.po.CtnCpaLog;

@Component
public class CTNCPALogDaoImpl extends AbstractCTNDAO implements CTNCPALogDao {

	@Override
	public Long saveLog(CtnCpaLog log) {
		getHibernateTemplate().save(log);
		return log.getLogId();
	}

	@Override
	public boolean saveLogBySql(final String[] properties, final Object[] values) {
		
		return (Boolean)getHibernateTemplate().execute(new HibernateCallback() {
			@Override
			public Object doInHibernate(Session s)
					throws HibernateException, SQLException {
				StringBuffer sql = new StringBuffer("insert into ctn_cpa_log (");
				StringBuffer sqlValue = new StringBuffer();
				int len = properties.length;
				for (int i = 0; i < len; i++) {
					sql.append(properties[i]);
					sqlValue.append(":").append(properties[i]);
					if (i < len - 1) {
						sql.append(", ");
						sqlValue.append(", ");
					}else{
						sql.append(" ");
						sqlValue.append(" ");
					}
				}
				sql.append(")").append(" values(").append(sqlValue.toString()).append(") ");
				SQLQuery qry = s.createSQLQuery(sql.toString());
				len = values.length;
				for (int k = 0; k < len; k++) {
					qry.setParameter(properties[k], values[k]);
				}
				return qry.executeUpdate() > 0;
			}
		});
	}
}
